
<template>
  <div class="Main">
    <div class="MainTitle">音色训练</div>
    <div class="MianContent">
      <div class="MainTopAction">
      </div>
      <div class="TableView">
        <div style="padding-left: 10px">
          <div class="flex">
            选择训练音色：
            <div>
              <a-select
                v-model="type"
                placeholder="选择音色"
                allowClear
                style="width: 220px"
                @change="selectType"
              >
                <a-select-option
                  :value="item.SpeakerID"
                  v-for="(item, index) in listData"
                  :key="index"
                >
                  {{ item.SpeakerID }}
                </a-select-option>
              </a-select>
              <div style="margin-top: 50px">
                <a-upload-dragger
                  v-model="fileList"
                  name="file"
                  :headers="headers"
                  :multiple="false"
                  :action="uploadUrl"
                  accept="audio/mp3,audio/wav"
                  :disabled="fileList.length >= 1"
                  @change="handleChange"
                  :beforeUpload="handleBeforeUpload"
                  @preview="handlePreview"
                  :showUploadList="false"
                >
                  <p class="ant-upload-drag-icon">
                    <a-icon type="inbox" />
                  </p>
                  <p class="ant-upload-text">上传音频</p>
                  <p class="ant-upload-hint" style="padding: 0 20px">
                    点击或拖拽文件上传，仅支持 mp3/wav 文件，仅可上传一个文件
                  </p>
                </a-upload-dragger>
                <div
                  style="padding: 20px 0 0; width: 100%"
                  class="flex align-center"
                  v-if="fileList.length"
                >
                  <audio
                    style="width: 100%"
                    :src="fileList[0].url"
                    controls="controls"
                  ></audio>
                  <a-icon
                    style="margin-left: 20px; font-size: 22px"
                    @click="delItem"
                    type="delete"
                  />
                </div>
                <div style="margin-top: 20px" v-if="fileList.length">
                  <a-button type="primary" @click="submitHandle"
                    >确定训练</a-button
                  >
                </div>
                <!-- <a-modal :visible="previewVisible" v-if="previewVisible" :footer="null" @cancel="handleCancel">
                <div style="padding: 20px;">
                  <audio src=""></audio>
                </div>
              </a-modal> -->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions } from "vuex";
import { showErrors, showError, showSuccess } from "@/utils/showMsg";
import Pagination from "@/components/common/pagination.vue";
import { DataSourceList } from "@/views/Columns/DataSource";
import UploadImage from "@/components/common/Upload";
import axios from 'axios';
import {
  GetAiVoiceList,
  TrainVoice
} from "@/api/api.js";
import env from "@/config/env";
import request from "@/utils/request";
import Vue from "vue";
import { ACCESS_TOKEN,USER_DATA } from '@/store/mutation-types';

export default {
  name: "list",
  components: {
    Pagination,
    UploadImage,
  },
  data() {
    return {
      total: 0, //定义初始有多少条数据
      pageno: 1, //默认第几页
      pagesize: 10, //一页显示多少条数据
      keyword: "",

      type:undefined,
      fileList:[],
      uploadUrl:`${env.baseURL}manager/fileUploadAndDownload/upload`,
      listData:[],
      headers: {
        Accept: 'application/json',
        Authorization: `${this.$ls.get(ACCESS_TOKEN)}`,
        'x-token':`${this.$ls.get(ACCESS_TOKEN)}`,
        'X-Requested-With':null
        // 'user-id':`${this.$ls.get(USER_DATA).UserId}`,

      //   config.headers['access-token'] = `${token}`
      // config.headers['user-id'] = `${userid.UserId}`
      // config.headers['market-id'] = `${userid.MarketId}`
      },
    };
  },
  computed: {
    ...mapState({}),
  },
  created() {},
  mounted() {
    let that = this;
    that.GetList();
  },
  methods: {
    ...mapActions({}),

    //
    handleBeforeUpload(file){
      console.log(file,'--')
    },

    handleChange(info) {
      console.log(info,'info')
      let fileList = [...info.fileList];
      fileList = fileList.map((file) => {
        // console.log(fileList);
        if (file.response) {
          if (file.response.code == 0) {
            file.url = file.response.data.file.url;
            file.id = file.response.data.file.ID;
          } else {
            file.status = 'error';
          }
        }
        return file;
      });
      console.log('fileList',fileList);
      this.fileList = fileList;
      // this.changeFileList(this.fileList);
    },

    handlePreview(file){
      console.log(file,'view')
    },

    selectType(){
      console.log(this.type,'==')
    },

    // 确定训练按钮
    async submitHandle(){
      const that = this;
      if(!that.type){
        showError('请选择训练音色')
        return
      }
      if(!that.fileList.length){
        showError('请上传训练音色文件')
        return
      }
      const formData = new FormData();
      formData.append('file',that.fileList[0].originFileObj)
      formData.append('speakerId',that.type)
      console.log(formData,'===');
      
      // let params = {
      //   file:formData,
      //   speakerId:that.type
      // }
      // let res = await TrainVoice(params)
      //   if(res.data.code == 0){
      //     showSuccess('训练成功！')
      //     that.fileList = [];
      //     that.type = undefined;
      //     that.GetList()
      //   }else{
      //     showError(res.data.msg)
      //   }
      
      const token = Vue.ls.get(ACCESS_TOKEN);
      axios({
        method:'post',
        url:`${env.baseURL}manager/ai/train`,
        data:formData,
        headers:{
          'x-token':token,
          Authorization:token,
          'Content-type': 'multipart/form-data',
        },
      }).then(res=>{
        console.log(res);
        if(res.data.code == 0){
          showSuccess('训练成功！')
          that.fileList = [];
          that.type = undefined;
          that.GetList()
        }else{
          showError(res.data.msg)
        }
      })
    },

    // 删除
    delItem(){
      const that = this;
      that.fileList = []
    },

    // 获取数据列表API
    async GetList() {
      let that = this;
      let params = {
        keywords: that.keyword,
        page: that.pageno,
        pageSize: that.pagesize,
      };
      const res = await GetAiVoiceList(params);
      if (res.data.code == 0) {
        // console.log(res.data);
        const data = res.data.data;
        if (data.length > 0) {
          data.forEach((item, index) => {
            item.key = item.SpeakerID;
            item.indexNum = index;
            // item.CreatedAt = new Date(item.CreatedAt).toLocaleString(); //地区时间转换
            item.CreateTime = that.$moment(item.CreateTime).format('YYYY-MM-DD  HH:mm:ss'); //时间戳转换成时间
          });
        }
        // console.log(data);
        // that.total = data.total;
        that.listData = data;
      } else {
        showError(res.data.msg);
      }
    },

  },
};
</script>

<style lang="less">
.Main {
  border-radius: 10px;
  overflow: hidden;
  background: #fff;

  .MainTitle {
    font-size: 24px;
    color: #333;
    margin: 10px 20px;
    position: relative;
  }

  .MainTitle:before {
    content: "";
    width: 40px;
    height: 12px;
    background: linear-gradient(
      270deg,
      rgba(0, 158, 238, 0) 0%,
      rgba(221, 169, 85, 0.3) 100%
    );
    position: absolute;
    bottom: 2px;
    left: 0;
  }

  .MianContent {
    padding: 10px 20px 20px 20px;

    .MainTopAction {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      justify-content: space-between;
    }

    .TabsItem {
      padding: 10px 0;
      width: 70px;
      position: relative;
      margin-right: 24px;
      text-align: center;
      cursor: pointer;
      margin-bottom: 20px;
      color: #000;
    }

    .TabsIndex {
      color: #dda955;
    }

    .TabsIndex::before {
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translate(-50%, 0%);
      width: 50px;
      height: 2px;
      background-color: #dda955;
    }
  }
}
</style>